import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:cached_network_image/cached_network_image.dart';

import 'index.dart';

class UserInfoPage extends GetView<UserInfoController> {
  const UserInfoPage({super.key});

  // 构建顶部区域（轮播图和用户信息）
  Widget _buildTopSection(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;
    final carouselWidth = screenWidth * 0.6; // 轮播图占屏幕宽度的60%
    
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
      child: Stack(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 轮播图部分 (60%宽度)
              SizedBox(
                width: carouselWidth,
                height: 180,
                child: Stack(
                  children: [
                    // 轮播图
                    Positioned.fill(
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(20), // 四个角进行圆弧裁剪
                        child: Obx(() => PageView.builder(
                          controller: controller.pageController,
                          onPageChanged: controller.updateCarouselIndex,
                          itemCount: controller.carouselImages.length,
                          itemBuilder: (context, index) {
                            return CachedNetworkImage(
                              imageUrl: controller.carouselImages[index],
                              fit: BoxFit.cover,
                              errorWidget: (context, url, error) => 
                                Container(
                                  color: Colors.grey[300],
                                  child: const Icon(Icons.image_not_supported, size: 50),
                                ),
                            );
                          },
                        )),
                      ),
                    ),
                    
                    // 页面指示器（暂时禁用）
                    Positioned(
                      bottom: 10,
                      left: 0,
                      right: 0,
                      child: Center(
                        child: Obx(() => Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: List.generate(
                            controller.carouselImages.length,
                            (index) => Container(
                              margin: const EdgeInsets.symmetric(horizontal: 2),
                              width: 6,
                              height: 6,
                              decoration: BoxDecoration(
                                shape: BoxShape.circle,
                                color: index == controller.currentCarouselIndex.value 
                                  ? Colors.white 
                                  : Colors.white54,
                              ),
                            ),
                          ),
                        )),
                      ),
                    ),
                  ],
                ),
              ),
              
              // 右侧用户信息部分
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.only(left: 16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      // 用户头像
                      Obx(() => ClipRRect(
                        borderRadius: BorderRadius.circular(35),
                        child: CachedNetworkImage(
                          imageUrl: controller.displayUserAvatar,
                          width: 70,
                          height: 70,
                          fit: BoxFit.cover,
                          errorWidget: (context, url, error) {
                            // 头像加载失败时显示默认头像
                            return Container(
                              width: 70,
                              height: 70,
                              decoration: BoxDecoration(
                                color: Colors.white.withValues(alpha: 0.3),
                                borderRadius: BorderRadius.circular(35),
                              ),
                              child: const Icon(Icons.person, size: 35, color: Colors.white),
                            );
                          },
                        ),
                      )),
                      
                      const SizedBox(height: 8),
                      
                      // 用户昵称（上方显示）
                      Obx(() => Text(
                        controller.displayUserName,
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                        textAlign: TextAlign.center,
                        overflow: TextOverflow.ellipsis,
                      )),
                      
                      const SizedBox(height: 6),
                      
                      // 用户等级（下方显示，只显示等级名称）
                      Obx(() => Container(
                        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 3),
                        decoration: BoxDecoration(
                          color: Colors.white.withValues(alpha: 0.2),
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Text(
                          controller.displayUserLevelName,
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 12,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      )),
                      
                      const SizedBox(height: 12),
                      
                      // 粉丝数和点赞数（并排显示）
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          Expanded(
                            child: Column(
                              children: [
                                Obx(() => Text(
                                  "${controller.displayUserFollowers}",
                                  style: const TextStyle(
                                    color: Colors.white,
                                    fontSize: 16,
                                    fontWeight: FontWeight.bold,
                                  ),
                                )),
                                const Text(
                                  "粉丝数",
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 12,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Container(
                            width: 1,
                            height: 30,
                            color: Colors.white.withValues(alpha: 0.3),
                          ),
                          Expanded(
                            child: Column(
                              children: [
                                Obx(() => Text(
                                  "${controller.displayUserLikes}",
                                  style: const TextStyle(
                                    color: Colors.white,
                                    fontSize: 16,
                                    fontWeight: FontWeight.bold,
                                  ),
                                )),
                                const Text(
                                  "点赞数",
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 12,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                      
                      const SizedBox(height: 12),
                      
                      // 🔥 交互按钮区域：根据用户关系显示不同按钮
                      Obx(() {
                        if (controller.isCurrentUser.value) {
                          // 当前用户查看自己，不显示任何按钮
                          return const SizedBox.shrink();
                        } else if (controller.isFriend.value) {
                          // 是好友，显示聊天按钮
                          return GestureDetector(
                            onTap: controller.navigateToChat,
                            child: Container(
                              width: double.infinity,
                              height: 28,
                              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                              decoration: BoxDecoration(
                                color: Colors.white.withValues(alpha: 0.3),
                                borderRadius: BorderRadius.circular(14),
                              ),
                              child: const Center(
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Icon(
                                      Icons.chat_bubble_outline,
                                      size: 12,
                                      color: Colors.white,
                                    ),
                                    SizedBox(width: 4),
                                    Text(
                                      "聊天",
                                      style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 11,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          );
                        } else {
                          // 不是好友，显示加好友按钮
                          return GestureDetector(
                            onTap: controller.addFriend,
                            child: Container(
                              width: double.infinity,
                              height: 28,
                              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                              decoration: BoxDecoration(
                                color: Colors.white.withValues(alpha: 0.3),
                                borderRadius: BorderRadius.circular(14),
                              ),
                              child: const Center(
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Icon(
                                      Icons.person_add_outlined,
                                      size: 12,
                                      color: Colors.white,
                                    ),
                                    SizedBox(width: 4),
                                    Text(
                                      "加好友",
                                      style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 11,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          );
                        }
                      }),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  // 构建用户信息卡片
  Widget _buildUserInfoCard() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 兴趣标签
          const Text(
            "爱好:",
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 16,
            ),
          ),
          const SizedBox(height: 8),
          // 显示用户爱好信息（从API获取或固定选项）
          Obx(() {
            final userHobbies = controller.displayUserHobbies;
            final allHobbies = ["吃", "喝", "玩", "乐", "购"];
            
            return Wrap(
              spacing: 8,
              runSpacing: 8,
              children: allHobbies.map((hobby) {
                // 如果用户有爱好数据，根据实际爱好显示状态；否则全部显示为选中
                bool isSelected = userHobbies.isEmpty ? true : userHobbies.contains(hobby);
                return _buildInterestTag(hobby, isSelected);
              }).toList(),
            );
          }),

          // 用户签名
          const SizedBox(height: 16),
          const Text(
            "个性签名:",
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 16,
            ),
          ),
          const SizedBox(height: 8),
          Obx(() => Text(
            controller.displayUserSignature,
            style: TextStyle(
              color: controller.displayUserSignature == '这个人很懒，什么都没留下' ? Colors.grey : Colors.black87,
              fontStyle: controller.displayUserSignature == '这个人很懒，什么都没留下' ? FontStyle.italic : FontStyle.normal,
            ),
          )),

          // 常出没地点
          const SizedBox(height: 16),
          const Text(
            "常出没地:",
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 16,
            ),
          ),
          const SizedBox(height: 8),
          Obx(() => Text(
            controller.displayUserFrequentPlaces,
            style: TextStyle(
              color: controller.displayUserFrequentPlaces == '未知' ? Colors.grey : Colors.black87,
            ),
          )),



          // 活动信息
          const SizedBox(height: 16),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                "活动进行时",
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 16,
                ),
              ),
              // 只有查看当前用户自己的主页时才显示历史记录按钮
              Obx(() => controller.isCurrentUser.value 
                ? GestureDetector(
                    onTap: () => controller.navigateToHistory(),
                    child: const Text(
                      "历史记录",
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  )
                : const SizedBox.shrink(),
              ),
            ],
          ),
          const SizedBox(height: 8),
          
          // 动态显示进行中的活动列表（与MyApplication2保持一致）
          Obx(() {
            // 🔥 修复：响应当前用户活动数据的变化
            final ongoingActivities = controller.displayOngoingActivities;
            
            // 如果是当前用户且正在加载，显示加载状态
            if (controller.isCurrentUser.value && controller.isLoadingUserActivities) {
              return Container(
                padding: const EdgeInsets.all(20),
                child: const Center(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      SizedBox(
                        width: 16,
                        height: 16,
                        child: CircularProgressIndicator(strokeWidth: 2),
                      ),
                      SizedBox(width: 8),
                      Text(
                        "加载活动数据中...",
                        style: TextStyle(
                          color: Colors.grey,
                          fontSize: 14,
                        ),
                      ),
                    ],
                  ),
                ),
              );
            }
            
            if (ongoingActivities.isEmpty) {
              return Container(
                padding: const EdgeInsets.all(20),
                child: const Center(
                  child: Text(
                    "暂无进行中的活动",
                    style: TextStyle(
                      color: Colors.grey,
                      fontSize: 14,
                    ),
                  ),
                ),
              );
            }
            
            return Column(
              children: ongoingActivities.map((activity) {
                final publishTime = controller.formatActivityTime(
                  activity.activityPublishTime
                );
                final title = activity.activityTitle;
                
                return _buildMyApplication2StyleActivityCard(
                  publishTime,
                  title,
                  () => controller.joinActivity(activity),
                );
              }).toList(),
            );
          }),
        ],
      ),
    );
  }

  // 构建MyApplication2样式的活动卡片
  Widget _buildMyApplication2StyleActivityCard(String time, String title, VoidCallback? onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        height: 50,
        margin: const EdgeInsets.only(bottom: 1),
        child: Column(
          children: [
            Expanded(
              child: Row(
                children: [
                  // 活动发布时间（左侧，占50%宽度）
                  Expanded(
                    flex: 1,
                    child: Container(
                      alignment: Alignment.centerLeft,
                      padding: const EdgeInsets.only(right: 5),
                      child: Text(
                        time,
                        style: const TextStyle(
                          fontSize: 12,
                          color: Colors.black87,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ),
                  // 活动标题（右侧，占50%宽度）
                  Expanded(
                    flex: 1,
                    child: Container(
                      alignment: Alignment.centerLeft,
                      padding: const EdgeInsets.only(right: 5),
                      child: Text(
                        title,
                        style: const TextStyle(
                          fontSize: 12,
                          color: Colors.black87,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ),
                  // 申请加入按钮（与MyApplication2的PublishUserHomeActivity布局一致）
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 2),
                    decoration: BoxDecoration(
                      color: const Color(0xFFD94841),
                      borderRadius: BorderRadius.circular(15),
                    ),
                    child: const Text(
                      "申请加入",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 12,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            // 分割线（与MyApplication2保持一致）
            Container(
              height: 1,
              color: Colors.grey[300],
            ),
          ],
        ),
      ),
    );
  }



  // 构建兴趣标签
  Widget _buildInterestTag(String tag, bool isSelected) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      decoration: BoxDecoration(
        color: isSelected ? const Color(0xFFD94841) : Colors.grey[300],
        borderRadius: BorderRadius.circular(20),
      ),
      child: Text(
        tag,
        style: TextStyle(
          color: isSelected ? Colors.white : Colors.grey[600],
        ),
      ),
    );
  }

  // 主视图
  Widget _buildView(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: [
          _buildTopSection(context),
          _buildUserInfoCard(),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // 设置状态栏样式
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.light,
    ));
    
    return GetBuilder<UserInfoController>(
      init: UserInfoController(),
      id: "user_info",
      builder: (_) {
        return Scaffold(
          backgroundColor: const Color(0xFFD94841),
          extendBodyBehindAppBar: true,
          appBar: AppBar(
            leading: IconButton(
              icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
              onPressed: () => Get.back(),
            ),
            backgroundColor: Colors.transparent,
            elevation: 0,
            centerTitle: true,
            title: const Text(
              "用户主页",
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          body: SafeArea(
            child: _buildView(context),
          ),
        );
      },
    );
  }
}
